package com.project.common.service;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.project.common.constant.RedisConstant;
import com.project.common.domain.dto.UserDTO;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Enumeration;

/**
 * @author: 陈刚
 * @blame:
 **/
public class BaseService {
    @Resource
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    protected HttpServletRequest request;

    /**
     * 获取登录用户信息
     * @return
     */
    protected UserDTO getLoginUser(){
        UserDTO userDTO = null;
        try {
            SaTokenInfo info= StpUtil.getTokenInfo();
            String userStr = (String) redisTemplate.opsForValue().get(RedisConstant.User.USER_LOGIN_INFO + info.tokenValue);
            userDTO = JSONUtil.toBean(userStr,UserDTO.class);
        }catch (Exception e){
            throw new RuntimeException("获取登录用户信息失败，请重新登录！"+e);
        }
        if(userDTO == null){
            throw new RuntimeException("获取登录用户信息失败，请重新登录！");
        }
        return userDTO;
    }

    /**
     * 获取请求的IP地址
     * @return
     */
    public String getIp() {
        JSONObject ho = new JSONObject();
        Enumeration e = request.getHeaderNames();
        String remoteIp;
        while (e.hasMoreElements()) {
            remoteIp = (String) e.nextElement();
            ho.put(remoteIp, request.getHeader(remoteIp));
        }
        remoteIp = request.getHeader("remote_addr");
        if (remoteIp == null || remoteIp.isEmpty()) {
            if (ho.get("X-Forwarded-For") == null && ho.get("x-forwarded-for") == null) {
                if (remoteIp == null || remoteIp.isEmpty()) {
                    remoteIp = request.getRemoteAddr();
                }
            } else {
                String xForwardedFor = ho.containsKey("X-Forwarded-For") ? ho.getStr("X-Forwarded-For") : ho.getStr("x-forwarded-for");
                if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
                    remoteIp = xForwardedFor.split(",")[0];
                }
            }
        }
        return remoteIp;
    }

}
